//
//  ACLiveChatAudienceViewController.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/3/30.
//

#import "ACLiveChatAudienceViewController.h"
#import "ACChatAudienceCell.h"
#import "ACChatAudienceLabelCell.h"
#import "ACMsgSendView.h"
#import <IQKeyboardManager.h>

@interface ACLiveChatAudienceViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) UITableView *tableview;
@property(nonatomic,strong) UIButton *speakerBtn;
@property(nonatomic,strong) ACMsgSendView *msgSendView;
@property (nonatomic, strong)NSMutableArray<ACMsgModel *>*msgModelArray;
@property(nonatomic,strong) NSMutableArray *feedbackArray;
@property(nonatomic,assign) int feedbackSelect;
@property(nonatomic,assign)BOOL isLinkMic;

@end

@implementation ACLiveChatAudienceViewController

-(ACMsgSendView *)msgSendView{
    if (!_msgSendView) {
        _msgSendView = [[ACMsgSendView alloc] init];
        _msgSendView.isOutScreen = NO;
    }
    return _msgSendView;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

        NSBundle *curB = [NSBundle BundleWithBundleName:ACLiteAVUISDK targetClass:[self class]];
        [_collectionView registerNib:[UINib nibWithNibName:@"ACChatAudienceLabelCell" bundle:curB] forCellWithReuseIdentifier:@"ACChatAudienceLabelCell"];
    }
    return _collectionView;
}

-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedRowHeight = 104;
        _tableview.backgroundColor = UIColorFromRGB(0xFFFFFF);
        [_tableview setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        NSBundle *curB = [NSBundle BundleWithBundleName:ACLiteAVUISDK targetClass:[self class] ];
        [_tableview registerNib:[UINib nibWithNibName:@"ACChatAudienceCell" bundle:curB] forCellReuseIdentifier:@"ACChatAudienceCell"];
    }
    return _tableview;
}

-(UIButton *)speakerBtn{
    if (!_speakerBtn) {
        _speakerBtn = [[UIButton alloc] initWithFrame:CGRectZero];
        _speakerBtn.backgroundColor = UIColorFromRGB(0xFF6048);
        _speakerBtn.layer.masksToBounds = YES;
        _speakerBtn.layer.cornerRadius = 16;
        [_speakerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_speakerBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        _speakerBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_speakerBtn setTitle:@"请求发言" forState:UIControlStateNormal];
        [_speakerBtn setImage:[UIImage imageWithName:@"icon_volume-mute" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
        [_speakerBtn setTitle:@"取消发言" forState:UIControlStateSelected];
        [_speakerBtn setImage:[UIImage imageWithName:@"icon_volume-notice" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateSelected];
        [_speakerBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -5)];
        [_speakerBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];
        
        [_speakerBtn addTarget:self action:@selector(clickSpeaker) forControlEvents:UIControlEventTouchUpInside];
    }
    return _speakerBtn;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.msgModelArray = [NSMutableArray array];
    self.view.backgroundColor = UIColorFromRGB(0xF4F5F8);
    self.title = @"互动";
    self.feedbackSelect = 0;
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectZero];
    line1.backgroundColor = UIColorFromRGB(0xE2E1E0);
    [self.view addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@1);
        make.top.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@58);
        make.top.equalTo(self.view).with.offset(1);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
    }];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectZero];
    line2.backgroundColor = UIColorFromRGB(0xE2E1E0);
    [self.view addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@1);
        make.top.equalTo(self.view).with.offset(58);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
    }];
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(60, 0, 53 + ACSafeAreaBottomHeight, 0));
    }];
    
    [self.view addSubview:self.speakerBtn];
    [self.speakerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@108);
        make.height.mas_equalTo(@32);
        make.right.equalTo(self.view).with.offset(-15);
        make.bottom.equalTo(self.tableview.mas_bottom).offset(-10);
    }];
    
    [self.view addSubview:self.msgSendView];
    [self.msgSendView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.mas_equalTo(53 + ACSafeAreaBottomHeight);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    @weakify(self)
    self.msgSendView.textHandler = ^(NSString * _Nonnull x) {
        DDLogInfo(@"%@",x);
        @strongify(self)
        // 要发送的消息
        [self buildMsgModelWithText:x];
    };
    self.feedbackArray = [NSMutableArray arrayWithObjects:@"",@"看好",@"谨慎",@"持续关注", nil];
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}
-(void)buildMsgModelWithText:(NSString *)text{
    ACMsgModel *msgModel = [[ACMsgModel alloc] init];
    msgModel.userName = @"我";
    msgModel.userMsg  = text;
    msgModel.userHeadImageUrl = [ACUserProfileManager shareInstance].userModel.avatar;
    [self.liveRoom sendRoomTextMsg:text callback:^(int code, NSString * _Nullable message) {
        DDLogInfo(@"sendRoomTextMsg-------%@--------code--%d",message,code);
    }];
    [self bulletNewMsg:msgModel];
}
- (void)bulletNewMsg:(ACMsgModel *)msgModel{
    [self.msgModelArray addObject:msgModel];
    [self.tableview reloadData];
}
-(void)setStatusLinkMic{
    // 连麦的状态，点击按钮 取消连麦
    self.isLinkMic = YES;
    [_speakerBtn setTitle:@"发言中" forState:UIControlStateNormal];
    [_speakerBtn setImage:[UIImage imageWithName:@"icon_volume-mute" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
    [_speakerBtn setSelected:NO];
}
-(void)resetStatus{
    // 恢复按钮的原始样子
    self.isLinkMic = NO;
    [_speakerBtn setTitle:@"请求发言" forState:UIControlStateNormal];
    [_speakerBtn setImage:[UIImage imageWithName:@"icon_volume-mute" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
    [_speakerBtn setTitle:@"取消发言" forState:UIControlStateSelected];
    [_speakerBtn setImage:[UIImage imageWithName:@"icon_volume-notice" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateSelected];
    [_speakerBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -5)];
    [_speakerBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.msgModelArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ACChatAudienceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACChatAudienceCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[ACChatAudienceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ACChatAudienceCell"];
    }
    [cell setupCellContent:self.msgModelArray[indexPath.row]];
    return  cell;
}


#pragma mark --UICollectionViewDelegateFlowLayout
//定义HeadView大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(0, 0);
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > 0) {
        NSString *text = self.feedbackArray[indexPath.row];
        CGSize size = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, 32)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}
                                                  context:nil].size;
        
        return CGSizeMake(size.width+50, 58);
    }
    return CGSizeMake(90, 58);
}

#pragma mark -UICollectionViewDataSource
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.feedbackArray.count;
}

#pragma mark 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ACChatAudienceLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ACChatAudienceLabelCell" forIndexPath:indexPath];
    if (indexPath.item == 0) {
        cell.feedbackImg.hidden = NO;
        cell.selectImg.hidden = YES;
        cell.titleLabel.hidden = YES;
    }else{
        cell.titleLabel.text = self.feedbackArray[indexPath.row];
    }
    return cell;
}


#pragma mark - UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.feedbackSelect == indexPath.item || self.feedbackSelect != 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.feedbackSelect inSection:0];
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }else{
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
        [self sendFeedBackSelectedIndex:indexPath.item];
    }
}

//点击发言
-(void)clickSpeaker{
    DDLogInfo(@"请求发言");
    if (self.isLinkMic) {
        // 退出连麦
        [self resetStatus];
        if (self.requestJoinMicHandler) {
            self.requestJoinMicHandler([[ACUserProfileManager shareInstance] getUserModel].user_id,_isLinkMic);
        }
    }else{
        [self.speakerBtn setSelected:!self.speakerBtn.selected];
        if (self.requestJoinMicHandler) {
            self.requestJoinMicHandler([[ACUserProfileManager shareInstance] getUserModel].user_id,!self.speakerBtn.selected);
        }
    }
}

//点击反馈
-(void)sendFeedBackSelectedIndex:(NSInteger)index{
    NSString *text = self.feedbackArray[index];
    if (self.liveID != nil && ![self.liveID isEqualToString:@""]) {
        [ACLiveRoomManager requestFeedBackWithLiveID:self.liveID feedBackStatus:(self.feedbackSelect - 1) requestCallback:^(int code, NSString * _Nullable message) {
            if (code == 0) {
                DDLogInfo(@"#反馈------# %@",text);
                self.feedbackSelect = (int)index;
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.feedbackSelect inSection:0];
                [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
            }else if(code == 400){
                [SVProgressHUD showErrorWithStatus:@"您已反馈，无需重新反馈"];
            }
        }];
    }
}
-(void)setLiveID:(NSString *)liveID{
    _liveID = liveID;
    DDLogInfo(@"-----setLiveID-------setLiveID###%@",self.liveID);
}
-(void)setLiveRoom:(TRTCLiveRoom *)liveRoom{
    _liveRoom = liveRoom;
    DDLogInfo(@"-----setLiveRoom-------shareInstance###%@####%@",[TRTCLiveRoom shareInstance],[[TRTCLiveRoom shareInstance] checkRoomJoined:nil]);
}
-(void)dealloc {
    //获取当前类名
    DDLogInfo(@"%@ dealloc",[NSString stringWithUTF8String:object_getClassName(self)]);
}

#pragma mark - JXCategoryListContentViewDelegate

/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

@end
